package com.woniuxy.shiro.controller;

import com.woniuxy.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController //
@RequestMapping("/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @RequestMapping("/login")
    public String login(User user){
        //1.获取到“当前用户”对象
        Subject currentUser = SecurityUtils.getSubject();
        //获取session
        Session session = currentUser.getSession();
        session.setAttribute("name","lisi");

        //2.判断用户是否认证过
        if (!currentUser.isAuthenticated()){


            //没有认证过   token  令牌
            String pwd = new SimpleHash("MD5",user.getPwd(),user.getAccount(),100).toString();
            UsernamePasswordToken token =
                    new UsernamePasswordToken(user.getAccount(),pwd);

            //判断用户是否勾选记住我
            if (user.isRm()){
                token.setRememberMe(true);//使用记住我功能
            }

            try {
                //当前用户携带令牌去认证，去找securitymanager进行认证
                //认证时可能会报异常，只要出现异常说明令牌有问题，账号密码有问题
                //不报任何异常表明账号密码没问题
                currentUser.login(token);
                //
                logger.info("认证成功");
                return "success";
            }catch (UnknownAccountException e){
                //账号不存在
                e.printStackTrace();
                //认证失败
                return "账号不存在";
            } catch (IncorrectCredentialsException e){
                e.printStackTrace();
                //密码错误
                return "密码错误";
            }
        }

        return "success";
    }
}
